/*
 * ItemQueue.java
 *
 * Created on July 17, 2003, 6:45 PM
 */

package org.infoset.xml.util;

import java.util.*;
import org.infoset.xml.*;

/**
 *
 * @author  alex
 */
public class ItemQueue extends EmptySource implements ItemDestination {
   
   List queue;
   boolean endReceived;
   
   public ItemQueue() {
      queue = new ArrayList();
   }

   public void send(Item e) 
      throws XMLException
   {
      synchronized (queue) {
         queue.add(e);
         if (e.getType()==Item.ItemType.DocumentEndItem) {
            endReceived = true;
         }
         queue.notify();
      }
   }
   
   public void replay(ItemDestination dest) 
      throws XMLException
   {
      synchronized (queue) {
         for (Iterator values=queue.iterator(); values.hasNext();) {
            Item i = (Item)values.next();
            replaySend(dest,i);
         }
      }
   }
   
   protected void replaySend(ItemDestination dest,Item i) 
      throws XMLException
   {
      dest.send(i);      
   }

   public Item receive() {
      synchronized (queue) {
         if (queue.size()==0) {
            if (endReceived) {
               return null;
            }
            try {
               queue.wait();
            } catch (InterruptedException ex) {
               // TODO: Should this go somewhere?
               ex.printStackTrace();
            }
         }
         return queue.size()==0 ? null : (Item)queue.remove(0);
      }
   }

}
